package liming.ai.code.v4.data;

import liming.tool.file.FileRW;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JavaCode extends FileInfo{
    private String code;
    private String md;

    private String testName;
    private Throwable e;
    public JavaCode(String packageName, String className,String code) {
        super(packageName, className);
        this.code=code;
    }

    public JavaCode setCode(String code) {
        this.code = code;
        return this;
    }

    public String getCode() {
        return code;
    }

    public JavaCode setMd(String md) {
        this.md = md;
        return this;
    }

    public String getMd() {
        return md;
    }

    public JavaCode setTestName(String testName) {
        this.testName = testName;
        return this;
    }

    public String getTestName() {
        return testName;
    }

    public JavaCode setThrowable(Throwable e) {
        this.e = e;
        return this;
    }

    public Throwable getThrowable() {
        return e;
    }

    public static JavaCode valueOf(FileInfo fileInfo, String code){
        return new JavaCode(fileInfo.getPackage(),fileInfo.getClassName(),code);
    }
    public FileInfo valueOf(){
        return new FileInfo(getPackage(),getClassName());
    }


    public boolean writeJavaFile() throws IOException {
        System.out.println("java文件写入中 " + getJavaFile().getAbsolutePath());
        FileRW.writeTextFile(getJavaFile(),getCode(),false);
        System.out.println("java文件写入完成 " + getJavaFile().getAbsolutePath());
        return true;
    }
    public boolean writeMdFile() throws IOException{
        System.out.println("md文件写入中 " + getMdFile().getAbsolutePath());
        FileRW.writeTextFile(getMdFile(),md,false);
        System.out.println("md文件写入完成 " + getMdFile().getAbsolutePath());
        return true;
    }
    public static JavaCode load(JSONObject object){
        JavaCode javaCode = new JavaCode(object.optString("package"), object.optString("name", "未定义"), object.optString("code", "未实现，舍弃"))
                .setMd(object.optString("md")).setTestName(object.optString("test", ""));
        javaCode.setVersion(object.optInt("version",1));
        System.out.println("预构建类:" + javaCode.getAllClassName() + " version: " + javaCode.getVersion());
        return javaCode;
    }

    public static List<JavaCode> loads(JSONArray array){
        ArrayList<JavaCode> list = new ArrayList<>();
        for (int i = 0; i < array.length(); i++)
            list.add(load(array.getJSONObject(i)));
        return list;
    }
}
